package com.future.allUtils.utils;

import cn.hutool.core.lang.UUID;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Component
public class UploadUtils {

    @Autowired
    private MinioClient minioClient;

    private static final List<String> PICTURE_TYPES = new ArrayList<>();
    private static final List<String> VIDEO_TYPES = new ArrayList<>();

    static {
        // 图片类型
        PICTURE_TYPES.add("jpg");
        PICTURE_TYPES.add("jpeg");
        PICTURE_TYPES.add("png");
        PICTURE_TYPES.add("gif");
        PICTURE_TYPES.add("bmp");
        PICTURE_TYPES.add("svg");
        PICTURE_TYPES.add("webp");

        // 视频类型
        VIDEO_TYPES.add("mp4");
        VIDEO_TYPES.add("flv");
        VIDEO_TYPES.add("mkv");
        VIDEO_TYPES.add("avi");
        VIDEO_TYPES.add("mov");
        VIDEO_TYPES.add("wmv");
        VIDEO_TYPES.add("mpeg");
    }

    public String uploadFile(MultipartFile file, int type) {
        if (type != 1 && type != 2) {
            return "参数传递错误";
        }

        if (file.isEmpty()) {
            return "文件是空的";
        }

        // 获取文件扩展名
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            return "文件名为空";
        }

        String fileExtension = getFileExtension(originalFilename);
        if (fileExtension == null) {
            return "无法获取文件扩展名";
        }

        // 验证文件类型
        if (type == 1 && !PICTURE_TYPES.contains(fileExtension.toLowerCase())) {
            return "不支持该图片类型";
        }
        if (type == 2 && !VIDEO_TYPES.contains(fileExtension.toLowerCase())) {
            return "不支持该视频类型";
        }

        String bucketName = type == 1 ? "picture" : "video";
        String objectName = generateObjectName(fileExtension);

        try {
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build()
            );
            return "http://47.110.147.12:19000/" + bucketName + "/" + objectName;
        } catch (Exception e) {
            throw new RuntimeException("上传文件失败: " + e.getMessage(), e);
        }
    }

    private String getFileExtension(String filename) {
        int dotIndex = filename.lastIndexOf('.');
        if (dotIndex > 0 && dotIndex < filename.length() - 1) {
            return filename.substring(dotIndex + 1);
        }
        return null;
    }

    private String generateObjectName(String extension) {
        return UUID.randomUUID().toString().replace("-", "") + "." + extension;
    }
}